/*
 * @Author: 朱自强
 * @Date: 2024-03-08 19:28:49
 * @LastEditors: 朱自强
 * @LastEditTime: 2024-03-11 09:43:26
 * @FilePath: \A-LOT-OF-TEST-VUE3\src\utils\utils.ts
 * @Description:
 *
 * Copyright (c) 2024 by 朱自强, All Rights Reserved.
 */
import type { MenuOption } from 'naive-ui'
import type { Component } from 'vue'
import { h } from 'vue'
import { NIcon } from 'naive-ui'
/**
 * 将数组转成树结构
 * @param {Array} data 数组
 * @param {String} key 依据哪个字段分层级
 * @param {String} parentPropName 层级字段名称
 * @param {String} childrenName 子集集合名称
 * @returns {Array} 返回结果，树形结构
 */
export function listToTree(
  data: any[],
  key: string,
  parentPropName: string,
  childrenName: string
): any[] {
  const result: any[] = []
  data.forEach((item: any) => {
    item[childrenName] = []
  })
  const map: any = {}
  data.forEach((item: any) => {
    map[item[key]] = item
  })
  data.forEach((item: any) => {
    const parent = map[item[parentPropName]]
    if (parent) {
      ;(parent[childrenName] || (parent[childrenName] = [])).push(item)
    } else {
      result.push(item)
    }
  })
  return result
}

/**
 * 树转数组
 * @param {Array} treeData 树结构数据
 * @param {String} childrenName 子集集合名称
 * @returns {Array} 返回结果，数组
 */
export function treeToList(treeData: any[], childrenName: string): any[] {
  const stack: any[] = treeData
  const data: any[] = []
  while (stack.length !== 0) {
    const pop: any = stack.pop()
    data.unshift(pop)
    const children = pop[childrenName]
    if (children) {
      for (let i = children.length - 1; i >= 0; i--) {
        stack.unshift(children[i])
      }
    }
  }
  return data
}
// 生成uuid
export function getUUID(): string {
  const s: any = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'
  const uuid = s.join('')
  return uuid
}

// 路由处理成菜单
export function routerAsMenu(routers: readonly any[]): MenuOption[] {
  let result: MenuOption[] = []
  result = routers.map((item: any) => {
    const menu: MenuOption = {
      // 名称
      label: item.meta.title,
      // 路径
      key: item.path,
      // 图标
      icon: renderIcon(item.meta.icon)
    }
    if (item.children && item.children.length > 0) {
      menu.children = routerAsMenu(item.children)
    }
    return menu
  })
  return result
}
// 图标渲染
function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) })
}
